package com.example.demo;

import com.alibaba.fastjson.JSON;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
import org.glassfish.jersey.media.sse.EventInput;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.*;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.PrintWriter;


@RestController
public class TestController {

    /**
     * 模型业务后台接收前端请求，调用远端请求，得到结果返回数据给前端
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/event-stream; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache,");
        response.setHeader("Connection", "keep-alive");

        PrintWriter writer = response.getWriter();

        Configuration clientConfig = new ClientConfig(JacksonJsonProvider.class);
        Client client = ClientBuilder.newClient(clientConfig).register(SseFeature.class);//f.build();
        WebTarget target = client.target("http://localhost:8080/test2");

        Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
        builder.header("Accept","text/event-stream");

        String conditions="{\"messages\":\"xxxxxxxx\"}";
        EventInput eventInput = builder.accept(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(conditions, MediaType.APPLICATION_JSON_TYPE), EventInput.class);
        System.out.println("eventInput-> "+ JSON.toJSONString(eventInput));
        while (!eventInput.isClosed()) {
            try {
                final InboundEvent inboundEvent = eventInput.read();

                if (inboundEvent == null) {
                    // connection has been closed
                    break;
                }
                String content = inboundEvent.readData(String.class);
                if(null == content)
                {
                    continue;
                }
                System.out.println("客户端333："+content);
                writer.println("data:"+content);
                writer.flush();
            }catch (Exception e){
                System.out.println(e);
            }
        }
        eventInput.close();
    }

    /**
     * 模型服务端返回数据
     * @param messages
     * @param request
     * @param response
     * @throws IOException
     * @throws InterruptedException
     */
    @PostMapping("/test2")
    public void test2(@RequestBody String messages, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache,");
        response.setHeader("Connection", "keep-alive");

        PrintWriter writer = response.getWriter();

        String str = "窗前明月光，疑是地上霜。举头望明月，低头思故乡。";
        for(int i=1;i<=str.length();i++){
            String content = str.substring(0,i);
            System.out.println("服务端111："+content);
            Thread.sleep(200);
            writer.println("data:"+content);
            writer.println();
            writer.flush();
        }

    }


}
